package com.tbit.main.controller;

import cn.hutool.core.collection.CollUtil;
import com.tbit.main.common.JsonResult;
import com.tbit.main.constant.RedisConstant;
import com.tbit.main.constant.SysConstant;
import com.tbit.main.exception.BaseException;
import com.tbit.main.pojo.AccountUser;
import com.tbit.common.entity.GPS.CarHistory;
import com.tbit.main.pojo.MainCar;
import com.tbit.main.service.*;
import com.tbit.main.util.Assert;
import com.tbit.common.utils.GPSUtil;
import com.tbit.main.util.DateTimeUtil;
import com.tbit.main.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 运维车辆轨迹查询
 *
 * @author LMY
 * @create 2021-04-08 10:13
 */
@RestController
@RequestMapping("/mainCarHistory")
public class MainCarHistoryController {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private MainCarService mainCarService;
    @Autowired
    private CalibrateService calibrateService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private HistoryService historyService;


    /**
     * 根据时间查询单个车辆轨迹
     */
    @RequestMapping("/getByTime")
    public JsonResult getByTime(String token, String machineNO, String startTime, String endTime, Integer mapType) throws Exception {
        Assert.hasLength(startTime, "System.startTime.notNull");
        Assert.hasLength(endTime, "System.endTime.notNull");
        Assert.notNull(machineNO, "Machine.machineNO.notNull");

        if (mapType == null) {
            mapType = SysConstant.GOOGLE;
        }

        /**获取车辆*/
        MainCar mainCarDB = mainCarService.getByMachineNO(machineNO);

        if (mainCarDB != null) {
            String GPSToken = redisService.get(RedisConstant.REDIS_GPS);
            if (GPSToken == null) {
                GPSToken = GPSUtil.login();
                redisService.add(RedisConstant.REDIS_GPS, GPSToken, 59 * 60 * 2);
            }

           /* *//**GPS查车*//*
            List<CarHistory> carHistories = GPSUtil.findhistorytrack(GPSToken, machineNO, startTime, endTime);
            *//**校准*//*
            if (carHistories != null) {
                calibrateService.calibrateGPSLastPosS(carHistories, mapType);
            }*/
            //获取查询的时间分段参数
            List<Map<String, Object>> searchParams = historyService.getSearchParams(machineNO, startTime, endTime,"machineNO",false);
            List<CarHistory> carHistoryList = new ArrayList<>();
            for (Map<String, Object> param : searchParams) {
                /*GPS查车*/
                List<CarHistory> carHistories = GPSUtil.findhistorytrack(GPSToken, machineNO, DateTimeUtil.getDateTimeStr((Date)param.get("startTime")), DateTimeUtil.getDateTimeStr((Date)param.get("endTime")));
                /*校准*/
                if (CollUtil.isNotEmpty(carHistories)) {
                    calibrateService.calibrateGPSLastPosS(carHistories, mapType);
                    carHistoryList.addAll(carHistories);
                }
            }
            return JsonResult.succ(carHistoryList);
        } else {
            throw new BaseException("Machine.notExist");
        }

    }


    /**
     * 查询所有车辆最后位置
     *
     * @param token
     * @param accountId
     * @param mapType
     * @return
     */
    @RequestMapping("/allLastPos")
    public JsonResult allLastPos(String token, Integer accountId, Integer mapType) throws Exception {
        Assert.notNull(accountId, "AccountUser.agentId.notNull");

        AccountUser accountUser = tokenService.getAccount(token);

        if (mapType == null) {
            mapType = SysConstant.GOOGLE;
        }


        /**获取所有车辆id*/
        List<MainCar> mainCars = mainCarService.getByAccountId(accountId);
        if (mainCars.size() > 0) {
            Map<String, String> mainCarNOMap = new HashMap<>();
            for (MainCar mainCar : mainCars) {
                mainCarNOMap.put(mainCar.getMachineNO(), mainCar.getMainCarNO());
            }

            List<String> machineNOs = mainCars.stream().map(MainCar::getMachineNO).collect(Collectors.toList());

            String GPSToken = redisService.get(RedisConstant.REDIS_GPS);
            if (GPSToken == null) {
                GPSToken = GPSUtil.login();
                redisService.add(RedisConstant.REDIS_GPS, GPSToken, 59 * 60 * 2);
            }
            /**GPS查车*/
            List<CarHistory> carHistories = GPSUtil.findlastpos(GPSToken, StringUtil.getString(machineNOs));
            for (CarHistory carHistory : carHistories) {
                if (mainCarNOMap.get(carHistory.getDevice_no()) != null) {
                    carHistory.setMainCarNO(mainCarNOMap.get(carHistory.getDevice_no()));
                }
            }

            /**校准*/
            if (carHistories != null) {
                calibrateService.calibrateGPSLastPosS(carHistories, mapType);
            }
            return JsonResult.succ(carHistories);
        } else {
            return JsonResult.succ(mainCars);
        }
    }

    /**
     * 查询单个车辆最后位置
     *
     * @param token
     * @param machineNO
     * @param mapType
     * @return
     */
    @RequestMapping("/mainLastPos")
    public JsonResult mainLastPos(String token, String machineNO, Integer mapType) throws Exception {
        Assert.notNull(machineNO, "Machine.machineNO.notNull");

        if (mapType == null) {
            mapType = SysConstant.GOOGLE;
        }

        /**获取所有车辆id*/
        MainCar mainCars = mainCarService.getByMachineNO(machineNO);
        if (mainCars != null) {

            String GPSToken = redisService.get(RedisConstant.REDIS_GPS);
            if (GPSToken == null) {
                GPSToken = GPSUtil.login();
                redisService.add(RedisConstant.REDIS_GPS, GPSToken, 59 * 60 * 2);
            }
            /**GPS查车*/
            List<CarHistory> carHistories = GPSUtil.findlastpos(GPSToken, mainCars.getMachineNO());

            /**校准*/
            if (carHistories != null) {
                calibrateService.calibrateGPSLastPos(carHistories.get(0), mapType);
                //补充车辆编号
                carHistories.forEach(carHistory -> {
                    if (StringUtils.isBlank(carHistory.getMainCarNO())){
                        carHistory.setMainCarNO(mainCars.getMainCarNO());
                    }
                });
            }

            return JsonResult.succ(carHistories.get(0));
        } else {
            throw new BaseException("Machine.notExist");
        }
    }

}
